package com.example.ai.controller;

import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/zhipu")
public class ZhiPuChatController {

    @Autowired
    private ZhiPuAiChatModel chatModel;

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "请问成都今天天气如何") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @PostMapping(value = "/ai/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "请用简单介绍一下成都的历史") String message) {
        var prompt = new Prompt(new UserMessage(message));
        Flux<ChatResponse> stream = chatModel.stream(prompt);
        return chatModel.stream(prompt)
                .handle((response, sink) -> {
                    // 安全检查所有可能为null的值
                    if (response != null &&
                            response.getResult() != null &&
                            response.getResult().getOutput() != null &&
                            response.getResult().getOutput().getText() != null) {

                        String text = response.getResult().getOutput().getText();
                        // 只发送非空文本
                        if (!text.isEmpty()) {
                            sink.next(text);
                        }
                    }
                    // 忽略null或空值，不调用sink.next()
                });
//        return chatModel.stream(prompt).flatMapSequential(res -> Flux.just(res.getResult().getOutput().getText()));
//        return chatModel.stream(prompt);
    }
}
